
package com.plian.system.service.pm.property.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.system.entity.pm.property.PropertyRecord;
import com.plian.system.mapper.pm.property.PropertyRecordMapper;
import com.plian.system.service.pm.property.IPropertyRecordService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  服务实现类
 *
 * @author jianglei
 * @since 2019-12-05
 */
@Slf4j
@Service
@AllArgsConstructor
public class PropertyRecordServiceImpl extends ServiceImpl<PropertyRecordMapper, PropertyRecord> implements IPropertyRecordService {


    @Override
    public List<PropertyRecord> getLatestByInitialIds(List<String> initialIds) {
        List<PropertyRecord> propertyRecords = list(Wrappers.<PropertyRecord>lambdaQuery().in(PropertyRecord::getInitialId, initialIds));
        Map<String, List<PropertyRecord>> recordMap = propertyRecords.stream().collect(Collectors.groupingBy(PropertyRecord::getInitialId));
        List<PropertyRecord> results = new ArrayList<>();
        for (String key : recordMap.keySet()){
            List<PropertyRecord> recordList = recordMap.get(key);
            if (recordList.size() == 1){
                results.add(recordList.get(0));
                continue;
            }
            recordList = recordList.stream().sorted(Comparator.comparing(PropertyRecord::getUpdateTime).reversed()).collect(Collectors.toList());
            results.add(recordList.get(0));
        }
        return results;
    }
}
